<script setup lang="ts">
import YkPagination from '@yk/components/pagination/YkPagination.vue'
import { Pages } from '@typings/pages'
import { Download, Plus } from '@element-plus/icons-vue'
import YkTableColumn from '@yk/components/table-column/YkTableColumn.vue'
import { ObjectUtil } from '@utils/object-util'
import { ElForm } from 'element-plus'
import { VideoDTO, VideoSaveForm } from '@/api/entity/video'
import { getSceneListAPI } from '@/api/scene'
import { addVideoAPI, delVideoAPI, editVideoAPI, getVideoListByPageAPI } from '@/api/video'
import { SceneDTO } from '@/api/entity/scene'
import { required } from '@utils/form-rule'
import { TableUtil } from '@utils/table-util'
import { MountedCheck } from '@/utils'

defineOptions({ name: 'VideoManage' })

const mc = new MountedCheck()
onMounted(() => {
  searchHandle()
  getSceneList()
  mc.end()
})
onActivated(() => {
  if (mc.isMounted()) return
  getSceneList()
  getTableData()
})
// region TODO 查询
const searchParams = reactive({
  name: '',
  groupId: ''
})
function searchHandle () {
  pages.pageNum = 1
  exportParams.value = ObjectUtil.copy(searchParams)
  getTableData()
}
// endregion

// region TODO 表格数据
const pages = reactive(new Pages())
const tableData = ref<VideoDTO[]>([])
function getTableData () {
  const loading = ElLoading.service()
  getVideoListByPageAPI({
    ...pages.getParams(),
    param: searchParams
  }).then((res) => {
    res.result().then((rdata) => {
      tableData.value = rdata.records
      pages.total = rdata.total
    })
  }).finally(loading.close)
}
function delTableItem (id: string) {
  ElMessageBox.confirm('删除当前摄像头？', '删除提醒').then(() => {
    delVideoAPI({ id }).then((res) => {
      res.result().then(() => {
        getTableData()
      })
    })
  })
}
// endregion

// region TODO 场景
const sceneList = shallowRef<SceneDTO[]>()
function getSceneList () {
  getSceneListAPI().then((res) => {
    res.result().then((rdata) => {
      sceneList.value = rdata.data
    })
  })
}
// endregion

// region TODO 导出
const exportParams = shallowRef<typeof searchParams>()
// endregion

// region TODO 添加/修改表单
const saveForm = ref(new VideoSaveForm())
const saveFormRules = {
  // AppKey
  appkey: [required('AppKey为必填项')],
  // 关联场景
  groupId: [required('关联场景为必填项')],
  // 摄像头名称
  name: [required('摄像头名称为必填项')],
  // 设备序列号
  number: [required('设备序列号为必填项')],
  // 通道
  passage: [required('通道为必填项')],
  // Secret
  secret: [required('Secret为必填项')]
}
const saveFormRef = shallowRef<InstanceType<typeof ElForm>>()

// 对话框
const saveFormDialogModel = ref(false)
function showSaveFormDialog (item?: VideoDTO) {
  saveFormDialogModel.value = true
  if (item) {
    nextTick(() => {
      ObjectUtil.updateVal(saveForm.value, item)
    })
  }
}
function closeSaveFormDialog () {
  saveFormRef.value.resetFields()
  saveForm.value.id = null
  saveFormDialogModel.value = false
}
function submitSaveForm () {
  saveFormRef.value.validate().then(() => {
    const loading = ElLoading.service()
    const params = ObjectUtil.copy(saveForm.value)
    const result = saveForm.value.id ? editVideoAPI(params) : addVideoAPI(params)
    result.then((res) => {
      res.result().then(() => {
        ElMessage.success('保存成功')
        closeSaveFormDialog()
        getTableData()
      })
    }).finally(loading.close)
  })
}
// endregion
</script>

<template>
  <div class="layout_view d-flex" style="min-height: 100%">
    <div class="c_card-page w-100">
      <div class="c_card_header c_card-title bor-divider-b">摄像头管理</div>
      <!--搜索表单-->
      <el-form inline class="c_form-search pt-16" @submit.prevent="searchHandle">
        <el-form-item label="摄像头名称">
          <el-input v-model="searchParams.name" placeholder="请输入摄像头名称搜索" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchParams.groupId" placeholder="全部场景" filterable clearable>
            <el-option value="">全部</el-option>
            <el-option v-for="item in sceneList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHandle">查询</el-button>
        </el-form-item>
      </el-form>
      <!--功能栏-->
      <div class="d-flex-between">
        <el-button type="primary" :icon="Plus as any" @click="showSaveFormDialog()">添加摄像头</el-button>
        <export-file url="/video/export" :params="exportParams">
          <el-button class="c_btn--export" :icon="Download as any">导出</el-button>
        </export-file>
      </div>
      <!--表格-->
      <el-table class="mt-16 c_table-page w-100" stripe :data="tableData">
        <el-table-column label="#" type="index" :index="TableUtil.indexMethod.bind(this, pages)" />
        <yk-table-column label="摄像头名称" prop="name" />
        <yk-table-column label="关联场景" prop="groupName" />
        <yk-table-column label="摄像头地址" prop="address" />
        <yk-table-column label="添加时间" prop="createdAt" sortable />
        <el-table-column label="操作" width="180px">
          <template #default="scope">
            <div class="c_table-operation">
              <!--<el-link type="primary" size="small">查看</el-link>-->
              <el-link type="primary" size="small" @click="showSaveFormDialog(scope.row)">编辑</el-link>
              <el-link type="danger" size="small" @click="delTableItem(scope.row.id)">删除</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-affix target=".c_table-page" position="bottom" :offset="0">
        <yk-pagination class="c_table-pagination-page" :pages="pages" @handle="getTableData" />
      </el-affix>
    </div>
    <!--添加/修改表单-->
    <el-dialog
      v-model="saveFormDialogModel" :title="saveForm.id ? '编辑摄像头' : '添加摄像头'" width="567px"
      :close-on-click-modal="false" draggable :modal="false"
      @close="closeSaveFormDialog"
    >
      <el-form
        ref="saveFormRef" class="c_form-save mt-20" :model="saveForm"
        :rules="saveFormRules"
        label-width="140px"
      >
        <el-form-item label="关联场景：" prop="groupId">
          <div class="d-flex-align-center">
            <el-select v-model="saveForm.groupId" placeholder="请选择关联场景">
              <el-option v-for="item in sceneList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <refresh-btn class="cursor-pointer ml-2 fs-24 color-primary" @click="getSceneList" />
          </div>
        </el-form-item>
        <el-form-item label="摄像头名称：" prop="name">
          <el-input v-model.trim="saveForm.name" placeholder="请输入摄像头名称" />
        </el-form-item>
        <el-form-item label="AppKey：" prop="appkey">
          <el-input v-model.trim="saveForm.appkey" placeholder="请输入AppKey" />
        </el-form-item>
        <el-form-item label="Secret：" prop="secret">
          <el-input v-model.trim="saveForm.secret" placeholder="请输入Secret" />
        </el-form-item>
        <el-form-item label="设备序列号：" prop="number">
          <el-input v-model.trim="saveForm.number" placeholder="请输入设备序列号" />
        </el-form-item>
        <el-form-item label="通道：" prop="passage">
          <el-input v-model.trim="saveForm.passage" placeholder="请输入通道" />
        </el-form-item>
        <el-form-item label="验证码：" prop="code">
          <el-input v-model.trim="saveForm.code" placeholder="请输入验证码" />
        </el-form-item>
        <el-form-item label="摄像头地址：" prop="address">
          <el-input v-model.trim="saveForm.address" placeholder="请输入摄像头地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="c_form__submit-btn">
          <el-button type="primary" plain @click="closeSaveFormDialog">取消</el-button>
          <el-button type="primary" @click="submitSaveForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
</style>
